package com.macro.mall.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.mapper.SapAccountMapper;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberLoginLogMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.RedisService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.util.JwtTokenUtil;
import com.macro.mall.portal.util.messageSend.MessageSend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberLoginLogMapper loginLogMapper;

    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SapAccountMapper sapAccountMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public CommonResult register(String username, String password, String telephone, String authCode, String nickname) {
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            return CommonResult.failed("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            return CommonResult.failed("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setNickname(nickname);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insertSelective(umsMember);
        umsMember.setPassword(null);

//        // 创建用户时，新增一条账户信息
//        SapAccount sapAccount = new SapAccount();
//        sapAccount.setMemberId(umsMember.getId());
//        sapAccount.setMemberName(umsMember.getNickname());
//        sapAccount.setAccountBalance(new BigDecimal(0));
//        sapAccount.setWaitIncomeProfit(new BigDecimal(0));
//        sapAccount.setWaitIncomeAmount(new BigDecimal(0));
//        sapAccount.setFreezeAmount(new BigDecimal(0));
//        sapAccountMapper.insertSelective(sapAccount);
        return CommonResult.success(null, "注册成功");
    }

    @Override
    public CommonResult generateAuthCode(String telephone) {

        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        String timeInMillisOldString = redisService.get("TIMESTAMP" + telephone);
        if (org.apache.commons.lang3.StringUtils.isEmpty(timeInMillisOldString)) {
            timeInMillisOldString = "0";
        }
        long timeInMillisOld = Long.parseLong(timeInMillisOldString);

        StringBuilder sb = new StringBuilder();
        //十分钟之内获取redis中的验证码发送
        System.out.println("时间差：" + (timeInMillis - timeInMillisOld));
        if (timeInMillis - timeInMillisOld < 600 * 1000L) {
            String au = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
            System.out.println("redis_code:" + au);
            if (org.apache.commons.lang3.StringUtils.isEmpty(au)) {
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    sb.append(random.nextInt(10));
                }
                //验证码绑定手机号并存储到redis
                redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
                redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, 600 * 1000L);
                redisService.set("TIMESTAMP" + telephone, String.valueOf(timeInMillis));
            } else {
                sb.append(au);
            }
        } else {
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                sb.append(random.nextInt(10));
            }
            //时间戳
            redisService.set("TIMESTAMP" + telephone, String.valueOf(timeInMillis));
            //验证码绑定手机号并存储到redis
            redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
            redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, 600 * 1000L);
            //redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
        }
        System.out.println("手机验证码" + sb);
        System.out.println("手机验证码超时时间：" + AUTH_CODE_EXPIRE_SECONDS);
        //TODO 调度短信接口，发送手机短信
        JSONObject jsonObject = MessageSend.sendPhoneValidCode(sb.toString(), telephone);
        if (null == jsonObject) {
            return CommonResult.failed("系统异常");
        }
        if ("success".equals(jsonObject.getString("status"))) {
            return CommonResult.success(jsonObject, "获取手机验证码成功");
        } else {
            return CommonResult.failed("获取手机验证码失败");
        }
    }

    @Override
    public CommonResult updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            return CommonResult.failed("该账号不存在");
        }
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            return CommonResult.failed("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        return CommonResult.success(null, "密码修改成功");
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getUmsMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
//            updateLoginTimeByUsername(username);
            insertLoginLog(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public CommonResult verifyLogin(String token) {
        if (StringUtils.isEmpty(token)) {
            return CommonResult.unauthorized(0);
        }
        String username = jwtTokenUtil.getUserNameFromToken(token);
        if (StringUtils.isEmpty(username)) {
            return CommonResult.unauthorized(0);
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.validateToken(token, userDetails)) {
            UmsMemberExample memberExample = new UmsMemberExample();
            memberExample.createCriteria().andUsernameEqualTo(username);
            List<UmsMember> members = memberMapper.selectByExample(memberExample);
            if (CollectionUtils.isEmpty(members)) {
                return CommonResult.unauthorized(userDetails);
            } else {
                return CommonResult.success(members.get(0));
            }
        }
        return CommonResult.unauthorized(userDetails);
    }

    @Override
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @Override
    public void setOnlineStatusOfSelf(String username, int status) {
        if (StringUtils.isEmpty(username)) {
            return;
        }
        UmsMemberExample memberExample = new UmsMemberExample();
        memberExample.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> umsMembers = memberMapper.selectByExample(memberExample);
        if (CollectionUtils.isEmpty(umsMembers))
            return;

        UmsMember member = umsMembers.get(0);
        member.setOnLineStatus(status);

        int result = memberMapper.updateByPrimaryKey(member);
        System.out.println(result);
    }

    /**
     * 添加登录记录
     *
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsMember member = getMemberByUsername(username);
        UmsMemberLoginLog loginLog = new UmsMemberLoginLog();
        loginLog.setMemberId(member.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(request.getRemoteAddr());
        loginLogMapper.insert(loginLog);
    }

    public UmsMember getMemberByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (memberList != null && memberList.size() > 0) {
            return memberList.get(0);
        }
        return null;
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone) {
        if (StringUtils.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        return authCode.equals(realAuthCode);
    }

}
